var actmember = require('../../../xc/model/member')
var acttoolv2 = require('../../../xc/sys/toolv2')
var app = getApp()
const chooseLocation = requirePlugin('chooseLocation');

Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    canIUseGetUserProfile: false,
    basicurl: app.globalData.basicurl
    
  },
  xcloaddata: function (options, config) {
    if(config.payment){
      this.setData({
        paymentconfig:config.payment
      })
    }
    if(config.wholesale){
     
      this.setData({
        wholesaleconfig:config.wholesale
      })
  }
    if(config.task){
        this.setData({
          taskconfig:config.task
        })
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

  
    if (options) {
      if (options.op == 'coupon') {
        this.showcoupon();
      }
    }
 

    this.getconfig(config)
  },
   //已登入传参数
   afterlogin: function (options, config, userinfo) {
    var that = this;

    that.setData({
      "member": userinfo
    })
    if (userinfo.member_id == 0) { //未登录

    } else { //已登入
      that.getloginconfig(config)
      that.updatesimplevipinfo();
      if (this.data.configclub && this.data.configclub.status == 1) {

        acttoolv2.getLocation().then(locres => {
          if (config.club.status == 1 && app.globalData.member.memberinfo.groupclubid) {
            that.getmycloubinfo();
          }
        })
      }

    }
  },
  // 登录注册
  login(e) {
    var that = this;
    console.log(e.currentTarget.dataset.status)
    if (e.currentTarget.dataset.status == -1) {
      app.xc_sys_config.authop.oppower("login").then(function (res) {
        console.log(res)

        that.setData({
          "member": app.globalData.member
        })
        that.updatesimplevipinfo();
      })
    }else{
      wx.navigateTo({
        url: '/xc_lshop/shop/user/vip/editinfor',
      })
    }
  },
  showservice(){
    var pcenterconfig=this.data.pcenterconfig;
    var data={}
    console.log("sssssssssss")
    console.log(pcenterconfig.service)

    if(pcenterconfig.service && pcenterconfig.service.status==1){
    console.log("ssaaaaaaaaaaa")

      data['img']=pcenterconfig.service.simg;
      data['title']=pcenterconfig.service.text;
      data['phone']=pcenterconfig.service.phone;

    this.selectComponent("#popup").init(data)
      
    }
   
  },
  //加载config配置--页面样式
  getconfig(config) {

    var that = this;
    var updatedata = {};
    if (config.prothem) {
      if (config.prothem.themcolor) {
        var themconfig = config.prothem.themcolor.config;
        updatedata['themconfig'] = themconfig
      }
      if (config.prothem.pcenter) {
        var pcenterconfig = JSON.parse(JSON.stringify(config.prothem.pcenter.config));

        var customStyle = config.prothem.pcenter.customStyle;

        console.log("customStyle")
        console.log(customStyle)
        if (pcenterconfig && pcenterconfig.top) {
          if (pcenterconfig.top.funbtn == 'white') {
            wx.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: '#000000'
            })
          }
        }
        if (pcenterconfig.module && pcenterconfig.module.list.length > 0) {
          pcenterconfig.module.list = this.changemodulelist(pcenterconfig.module.list)
        } else {
          if (!pcenterconfig.module) {
            pcenterconfig.module = {}
          }
          pcenterconfig.module.list = []
        }

        if(!pcenterconfig.defaultclub){
          pcenterconfig.defaultclub={status:1}
        }

        updatedata['pcenterconfig'] = pcenterconfig;
        console.log("pcenterconfig")
        console.log(pcenterconfig)

        updatedata['customStyle'] = customStyle;
      }

    }
    if (config.rebate) {
      updatedata['configrebate'] = config.rebate;

    }
    if (config.club) {
      updatedata['configclub'] = config.club;
    }
    if (config.order) {
      if (config.order.comment) {
        updatedata['commentconfig'] = config.order.comment
      } else {
        updatedata['commentconfig'] = 1
      }
    } else {
      updatedata['commentconfig'] = 1
    }

    if (config.vip) {

      updatedata['configvip'] = config.vip;
    } else {
      updatedata['configvip'] = {
        status: -1
      };
    }
    if (config["delivery_config"]) {
      updatedata['delivery_config'] = config["delivery_config"]
    }
    // var  {delivery_config}= paytool.getnav(config,clubmode,clubmust)

    that.setData(updatedata)
  },
  //获取登入后config配置 -- prothem
  getloginconfig(config) {
    var that = this;
    var updatedata = {};
    if (config.prothem) {
      var pcenterconfig = JSON.parse(JSON.stringify(config.prothem.pcenter.config))
      if (pcenterconfig.module) {
        var modulelist = that.changemodulelist(pcenterconfig.module.list, app.globalData.member)
        updatedata['pcenterconfig.module.list'] = modulelist;
      }
    }
    that.setData(updatedata)
  },
  //获取手机号码
  getPhoneNumber(e) {

    var app = getApp()
    var that = this;
    var dataset = e.currentTarget.dataset;
    var isreg = -1;
    if (that.data.member.member_id) {
      isreg = 1;
    }
    var encryptedData = e.detail.encryptedData;
    var iv = e.detail.iv;
    var code = e.detail.code;

    var that = this;
    app.util.request({
      'url': 'entry/wxapp/sys_reg',
      showLoading: false,
      method: 'POST',
      data: {
        op: 'getphone',
        encryptedData: encryptedData,
        iv: iv,
        isreg: isreg,
        code:code
      },
      success(res) {


        var parm = res.data.data;
        if (parm["status"] == 1) {
          // var updatemodel = {};
          // updatemodel["usermodel.phone"] = parm["obj"].phoneNumber;
          if (dataset.op == 'authphone') {
            app.globalData.member = parm.obj;
            that.setData({
              member: parm.obj
            })
            wx.showToast({
              icon: "success",
              title: '授权成功',
            })
          } else
          if (dataset.op != "modfily") {
            if (isreg == 1) {
              app.globalData.member = parm.obj;
              that.successreg(parm.obj);
            }
          }
          // that.setData(updatemodel)
        } else {
          wx.showModal({
            title: '提示',
            content: parm["message"],
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
  
  updatesimplevipinfo() {
    var that = this;
    actmember.simplevipinfo().then(function (res) {
      if (res["status"] == 1 && res["obj"]) {
        var updatemodel = {}
        updatemodel["member.memberinfo.score"] = res["obj"]["score"]
        updatemodel["member.memberinfo.money"] = res["obj"]["money"]
        updatemodel["member.memberinfo.amount"] = res["obj"]["amount"]
        updatemodel["member.memberinfo.exp"] = res["obj"]["exp"]

        updatemodel["member.memberinfo.vipinfo"] = res["obj"]["vipinfo"]
        updatemodel["member.memberinfo.couponnum"] = res["obj"]["couponnum"]
        updatemodel["member.memberinfo.unusedamount"] = res["obj"]["unusedamount"]
        updatemodel["member.memberinfo.allactivaamount"] = res["obj"]["allactivaamount"]

        updatemodel["order"] = res["obj"]["order"]


        console.log(updatemodel)
      }
      that.setData(updatemodel)
    })

  },
  //模块权限判断
  changemodulelist(modulelist, member) {
    console.log(modulelist.length)

    if (modulelist && modulelist.length > 0) {
      modulelist.forEach(listitem => {
        if (listitem.navlist) {
          var navlist = listitem.navlist;
          for (var i = 0; i < navlist.length; i++) {
            var navitem = navlist[i]

            if (!navitem['url'] && navitem['cid'] == 1) {
              navlist.splice(i, 1)
              i--;
            } else if (navitem['url'] == '/xc_lshop/business/work/index') {
              if (member) {
                if (member.member_id == 0 || (member.member_id && member.memberinfo && member.memberinfo.authority != 2)) {
                  navlist.splice(i, 1)
                  i--;

                }
              } else {
                navlist.splice(i, 1)
                i--;

              }
            }
          }
        }
      });
      return modulelist
    }



  },
 
  getmycloubinfo() {
    var app = getApp()
    if (app.globalData.clubinfo) {
      this.setData({
        clubinfo: app.globalData.clubinfo
      })
    } else {
      actmember.getmycloubinfo().then(res => {
        if (res["status"] == 1) {
          console.log("res")
          console.log(res)
          var obj = res["obj"]
          if (obj['status'] == 1 && obj['islock'] == -1) {
            var clubinfo = res["obj"]
            if (app.globalData.lng) {
              var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
              clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
            }
            app.globalData.clubinfo = clubinfo;
            this.setData({
              clubinfo: clubinfo
            })
          }



        }
      })
    }
    // app.globalData.clubinfo 

  },
  setaddr() {
    var address = this.selectComponent("#address");
    address.showaddresslist();
  },
  getmodel: function (id) {
    var that = this;
    actbill.getmodel(id).then(res => {
      if (res.status == 1) {
        that.setData({
          xcmodel: res.obj
        })

      }
    })
  },

  setgroupaddr: function (e) {

    var clubaddress = this.selectComponent("#clubaddress")
    clubaddress.showselect(e)
  },
  //团队选择返回
  selectgroupaddr: function (ev) {
    var app = new getApp()

    app.globalData.clubinfo = ev.detail;
    var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, ev.detail.lng, ev.detail.lat)

    actmember.setclub(ev.detail.id).then(res => {

    })
    this.setData({
      clubinfo: ev.detail
    })

  },
  /**优券 */
  couponblack: function () {

  },
  /**显示优惠券 */
  showcoupon: function () {
    var that = this;
    this.authop("coupon").then(rest => {
      if (rest["status"] != 1) {
        wx.showToast({
          title: rest["message"] ? rest["message"] : "获取信息失败",
        })
      } else {
        var Comcouponpro = that.selectComponent("#centercouponpro")
        Comcouponpro.showinfo()
      }
    })
  },
  // 功能跳转
  tourl: function (e) {
    var app = getApp()
    var that = this;

    app.xc_sys_config.authop.oppower("login").then(function (res) {
      var dataset = e.currentTarget.dataset;
      if (dataset.url == "/xc_lshop/setaddr") {
        that.setaddr();
      } else if (dataset.url == "/xc_lshop/showcoupon") {
        that.showcoupon();
      } else {
        wx.navigateTo({
          url: dataset.url,
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  mapnavigation() {
    var app = getApp()
    var latitude = parseFloat(app.globalData.clubinfo.lat)
    var longitude = parseFloat(app.globalData.clubinfo.lng)
    var name = app.globalData.clubinfo.title
    var address = app.globalData.clubinfo.province + app.globalData.clubinfo.city + app.globalData.clubinfo.county + app.globalData.clubinfo.addrinfo

    wx.openLocation({
      latitude,
      longitude,
      scale: 18,
      name: name,
      address: address
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {

    const location = chooseLocation.getLocation();


    if (location) {

      var addresslist = this.selectComponent("#address");
      var addform = addresslist.selectComponent("#addform")
      addform.chooseLocation(location)
    }

    if (this.data.member) {

      this.setData({
        "member": app.globalData.member
      })
    }
    this.updatesimplevipinfo();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //授权用户信息
  GetUserProfile(e) {
    var that = this;


    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        var app = getApp()
        var encryptedData = res.encryptedData;
        var iv = res.iv;
        var that = this;
        var isreg = -1;

        app.util.request({
          'url': 'entry/wxapp/sys_reg',
          showLoading: false,
          method: 'POST',
          data: {
            op: 'weixiinfo',
            encryptedData: encryptedData,
            iv: iv,
            isreg: isreg
          },
          success(res) {

            var parm = res.data.data;
            if (parm["status"] == "41009") {
              wx.setStorageSync('userInfo', '');
              that.GetUserProfile(null);
              return;
            }
            if (parm.status == 1) {
              var obj = parm['obj'];
              that.setData({
                'member.memberinfo.nickname': obj['nickName'],
                'member.memberinfo.headimgurl': obj['avatarUrl'],
                'member.nickname': obj['nickName'],
                'member.headimgurl': obj['avatarUrl'],
              })
              app.globalData.member.nickname = obj['nickName'];
              app.globalData.member.headimgurl = obj['avatarUrl'];
              app.globalData.member.memberinfo.nickname = obj['nickName'];
              app.globalData.member.memberinfo.headimgurl = obj['avatarUrl'];


            }
          },
          fail(res) {}
        })
      }
    })


  },

})